﻿using Kingdee.BOS;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;
using System.Diagnostics;

namespace Caraya.MFG.BillPlugIn
{
    [Description("pdf文件签署"), HotUpdate]
    public class PurPdf : AbstractBillPlugIn
    {
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            switch (e.BarItemKey)
            {
                // 文件签署
                case "tbSign":
                    FileSign();
                    break;
                default:
                    break;
            }
        }

        private void FileSign()
        {
            var pkId = (string)this.View.Model.GetPKValue();
            var FormId = this.View.BusinessInfo.GetForm().Id;
            // 供应商
            var Provider = (DynamicObject)this.Model.GetValue("FProviderId");
            var ProviderName = Provider == null ? "" : ((LocaleValue)Provider["Name"])[2052];

            // 采购员
            var Purchaser = (DynamicObject)this.Model.GetValue("FPurchaserId");
            var PurchaserName = Purchaser == null ? "" : ((LocaleValue)Purchaser["Name"])[2052];
            var Remarks = (LocaleValue)this.Model.GetValue("F_SOL_Remarks");

            // 明细
            var entity = this.Model.BillBusinessInfo.GetEntryEntity("FPOOrderEntry");
            var POOrderEntry = this.Model.GetEntityDataObject(entity);
            var BillNo = this.Model.GetValue("FBillNo");
            Guid guid = Guid.NewGuid();
            string randomCode = guid.ToString("N").Substring(0, 8);

            var obj = new JSONObject();
            obj.Put("code", 200);
            obj.Put("sucess", true);
            obj.Put("msg", "成功");
            var data = new JSONObject();
            data.Put("contractId", BillNo);
            data.Put("interfaceId", "Xingkong9876543210");
            data.Put("transactionId", randomCode);
            //data.Put("proposer_name", "");
            var parameterMap = new JSONObject();
            parameterMap.Put("${contract_code}", BillNo);
            parameterMap.Put("${supplier_code}", Provider["Number"]);
            data.Put("parameterMap", parameterMap);
            var dynamicTable = new JSONObject();
            var table_0 = new JSONArray();
            var t0_0 = new string[] { "南京中安半导体设备有限责任公司", "A AND W SYSTEMS" };
            var t0_1 = new string[] { "南京市浦口区顶山街道雨合路6号光电科技园A栋1楼", "" };
            var t0_2 = new string[] { "admin", "" };
            table_0.Add(t0_0);
            table_0.Add(t0_1);
            table_0.Add(t0_2);
            dynamicTable.Put("table_0", table_0);
            var table_1 = new JSONArray();
            var t1_0 = new string[] { "经南京中安半导体设备有限责任公司与供应商协商一致，就南京中安半导体设备有限责任公司向供应商购买产品事宜，达成以下协议，双方共同遵守", "", "", "", "", "", "", "", "" };
            //var t1_1 = new string[] { "", "", "", "", "", "", "", "", "" };
            //var t1_2 = new string[] { "", "", "", "", "", "", "", "", "" };
            table_1.Add(t1_0);
            //table_1.Add(t1_1);
            //table_1.Add(t1_2);
            foreach (var item in POOrderEntry)
            {
                var Material = (DynamicObject)item["MaterialId"];
                var fnumber = Material["Number"];                               // 物料编码
                var fname = Material["Name"] as LocaleValue;                    // 物料名称
                var fSpecification = Material["Specification"] as LocaleValue;  // 型号规格
                var Unit = (DynamicObject)item["UnitId"];
                var fUnit = Unit["Name"] as LocaleValue;                        // 单位
                var fDeliveryDate = (string)item["DeliveryDate"];               // 交货日期
                var t1_dynamic = new object[] { fnumber, fname[2052], fSpecification[2052], fUnit[2052], item["Qty"], item["TaxRate"], item["TaxPrice"], item["TaxAmount"], fDeliveryDate };
                table_1.Add(t1_dynamic);
            }
            dynamicTable.Put("table_1", table_1);
            var table_2 = new JSONArray();
            var t2_0 = new string[] { "小网", "小易" };
            var t2_1 = new string[] { "小云", "小音" };
            var t2_2 = new string[] { "小乐", "天马" };
            table_2.Add(t2_0);
            table_2.Add(t2_1);
            table_2.Add(t2_2);
            dynamicTable.Put("table_2", table_2);
            var table_3 = new JSONArray();
            var t3_0 = new string[] { "南京中安半导体设备有限责任公司", "A AND W SYSTEMS" };
            var t3_1 = new string[] { "中国（江苏）自由贸易试验区南京片区研创园团结路 99 号孵鹰大厦 1836 室", "" };
            var t3_2 = new string[] { "91320191MA212QCU5D", "" };
            var t3_3 = new string[] { "宁波银行股份有限公司南京江北新区支行", "Bank of America" };
            var t3_4 = new string[] { "72260122000004165", "3251 6488 3330" };
            var t3_5 = new string[] { "", "" };
            var t3_6 = new string[] { "2022-8-23", "2022-8-23" };
            table_3.Add(t3_0);
            table_3.Add(t3_1);
            table_3.Add(t3_2);
            table_3.Add(t3_3);
            table_3.Add(t3_4);
            table_3.Add(t3_5);
            table_3.Add(t3_6);
            dynamicTable.Put("table_3", table_3);
            data.Put("dynamicTable", dynamicTable);
            obj.Put("data", data);
            Debug.WriteLine(obj.ToJSONString());
            //var url = "/notify/xingkong/onpush";
            //var resultJson = Kingdee.BOS.KDNetwork.HttpClient.HttpPost(url, obj);
            //var resultObject = JSONObject.Parse(resultJson);
            //if (resultObject.GetValue<int>("code", 0) == 200)
            //{
            //    var pdfInfo = resultObject.GetValue<JSONObject>("data", new JSONObject());
            //    var pdfUrl = pdfInfo.GetValue<string>("download_url", "");
            //    var pdfName = pdfInfo.GetValue<string>("file_name", "");

            //    using (HttpClient client = new HttpClient())
            //    {
            //        HttpResponseMessage response = client.GetAsync(pdfUrl).Result;
            //        response.EnsureSuccessStatusCode();
            //        Stream responseStream = response.Content.ReadAsStreamAsync().Result;
            //        MemoryStream memoryStream = new MemoryStream();
            //        responseStream.CopyTo(memoryStream);
            //        byte[] fileData = memoryStream.ToArray();
            //        string base64EncodedData = Convert.ToBase64String(fileData);

            //        var AttObject = new JSONObject();
            //        AttObject.Put("FileName", pdfName);
            //        AttObject.Put("FormId", FormId);
            //        AttObject.Put("IsLast", true);
            //        AttObject.Put("InterId", pkId);
            //        AttObject.Put("BillNO", BillNo);
            //        AttObject.Put("AliasFileName", pdfName);
            //        AttObject.Put("SendByte", base64EncodedData);
            //        WebApiServiceCall.AttachmentUpload(this.Context, AttObject.ToJSONString());
            //    }
            //}
        }
    }
}
